package com.bsoft.gol.editor.init;

import com.bsoft.gol.editor.utils.UserRoleTokenUtils;
import ctd.account.UserRoleToken;
import ctd.spring.AppDomainContext;
import ctd.util.ServletUtils;
import ctd.util.context.ContextUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * description
 *
 * @author neoLin - 2023/03/07 10:46
 **/
@Slf4j
@WebFilter(urlPatterns = { "*" })
public class UserTokenFilter implements Filter {
    /**
     * 初始化，只在项目启动的时候执行一次
     */
    @Override
    public void init(FilterConfig filterConfig)  throws ServletException{
        log.info("===> UserTokenFilter init");
    }
    /**
     * 用于存放过滤器的业务逻辑实现代码
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        try {
            log.info("===> UserTokenFilter doFilter");
            UserRoleToken token = UserRoleTokenUtils.getUserRoleToken(httpRequest);
            log.info("===> UserTokenFilter doFilter token : " +(token==null));
            String currentDeptId = UserRoleTokenUtils.getCurrentDeptId(httpRequest);
            Map<String, Object> headers = new HashMap();
            headers.put("$uid", token.getUserId());
            headers.put("$urt", token.getId());
            headers.put("$tenantId", token.getTenantId());
            headers.put("currentDeptId", currentDeptId);
            headers.put("$clientIpAddress", ServletUtils.getIpAddress(httpRequest));
            headers.put("$fromDomain", AppDomainContext.getName());
            headers.put("$ur", token);
            ContextUtils.put("$rpcInvokeHeaders", headers);
            ContextUtils.put("$ur", token);
            ContextUtils.put("currentDeptId", currentDeptId);
            ContextUtils.put("$clientIpAddress", ServletUtils.getIpAddress(httpRequest));
            ContextUtils.put("$fromDomain", AppDomainContext.getName());
        } catch (Exception var7) {
            log.info("解析token失败,{}", var7.getMessage());
        }

        filterChain.doFilter(httpRequest, response);
        ContextUtils.clear();
    }

    /**
     * 销毁，在项目关闭，Servlet 容器销毁前调用
     */
    @Override
    public void destroy() {
        log.info("===> UserTokenFilter destroy");
    }
}
